package com.sc.ppx_api.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.ppx_api.pojo.Users;
import com.sc.ppx_api.service.IUsersService;
import com.sc.ppx_api.utils.JwtUtils;
import com.sc.ppx_api.utils.RedisUtils;
import com.sc.ppx_api.utils.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 用户基础信息表 前端控制器
 * </p>
 *
 * @author victory
 * @since 2025-09-22 10:50:19
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    IUsersService usersService;
    @Autowired
    RedisUtils redisUtils;

    private String generateRandomString(int length){
        if (length <= 0){
            throw new IllegalArgumentException("长度需大于0");
        }
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            char randomChar = (char) ('a'+random.nextInt(26));
            builder.append(randomChar);
        }
        return builder.toString();

    }

    @RequestMapping("login")
    ResponseMsg login(@RequestBody Users users){
        log.info("用户登录数据{}", users);
        String accountOrEmail = users.getAccount();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        if (accountOrEmail.contains("@")){
            wrapper.eq("email", accountOrEmail);
        }else {
            wrapper.eq("account", accountOrEmail);
        }
        Users ret = usersService.getOne(wrapper);
        if (null == ret){
            return ResponseMsg.getInstance(ResponseMsg.ACCOUNT_ERROR, "账号不存在");
        }
        String password = DigestUtils.md5DigestAsHex((users.getPassword()+ret.getSalt()).trim().getBytes());
        for (int i = 0; i < ret.getRepwdTimes(); i++){
            password = DigestUtils.md5DigestAsHex(password.getBytes());
        }
        System.out.println("数据库中密码:"+ret.getPassword());
        System.out.println("当前密码:"+password);
        if (ret.getPassword().equals(password)){
            String token = JwtUtils.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(ret), 3600*24);
            log.info("生成的token: {}", token);
            redisUtils.set(ret.getAccount(), token);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "登录成功", token);
        }
        System.out.println("密码错误");
        return ResponseMsg.getInstance(ResponseMsg.ERROR, "密码错误");

    }

    @RequestMapping("register")
    ResponseMsg register(@RequestParam String account, @RequestParam String email, @RequestParam String password){
        if (null != account && null != email && null != password){
            Users users = new Users();
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("account", account);
            if (usersService.exists(wrapper)){
                System.out.println("用户名已存在");
                return ResponseMsg.getInstance(ResponseMsg.ACCOUNT_ERROR, "用户名已存在");
            }
            Random random = new Random();
            LocalDateTime dateTime = LocalDateTime.now();
            users.setCreateTime(dateTime);
            users.setAccount(account);
            users.setEmail(email);
            String salt = generateRandomString(random.nextInt(10)+6);
            users.setSalt(salt);
            int times = random.nextInt(1024)+10;
            users.setRepwdTimes(times);
            //第一次加密
            String pwd = DigestUtils.md5DigestAsHex((password+salt).getBytes());
            //多次加密
            for (int i = 0; i < times; i++) {
                pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
            }
            users.setPassword(pwd);
            if (usersService.save(users)){
                System.out.println("注册成功,"+users);
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "注册成功");
            }
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "注册失败");
        }
        return ResponseMsg.getInstance(ResponseMsg.ERROR, "必填字段不能为空");
    }

}
